package common

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var Key = "YXNkZmFzZGZhc2ZzZGYxMjNycnFyd2VmYWVmcXdlZg=="

type testClaims struct {
	Username string `json:"username"`
	Uid      uint   `json:"id"`
	jwt.StandardClaims
}

func GenToken(username string, uid uint) string {
	claims := testClaims{
		username, uid,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 24 * 7).Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "service",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	//要传一个 []byte ?
	tokenStr, err := token.SignedString([]byte(Key))
	if err != nil {
		//Todo 错误处理
		fmt.Println("Key", Key)
		fmt.Println("token.SignedString", tokenStr)
		fmt.Println("error", err.Error())
	}
	return tokenStr
}

func ParseToken(tokenStr string) (*jwt.Token, testClaims, error) {
	claims := testClaims{}
	token, err := jwt.ParseWithClaims(
		tokenStr,
		&claims,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(Key), nil
		})
	return token, claims, err
}
